import React, { useState, useEffect, useRef } from 'react'
import { Card, Col, Row, List, Calendar, message, notification } from 'antd'
import _ from 'lodash'
import * as echarts from 'echarts'
import { formatTimeLimit } from '../../../utils/time'
import { getHomeInformation } from '../../../utils/request/get'
import './index.css'
import { configLocale } from '../../../utils/common';
import { setCache } from '../../../utils/cache'
import { useSelector } from 'react-redux'

export default function Home() {
    const [timeLimit, setTimeLimit] = useState([])
    const [riskLevels, setRiskLevels] = useState([])
    const token = useSelector(state => state.TokenReducer.token)
    const categoryRef = useRef()
    const border = true

    useEffect(() => {
        const handleEmergent = (data) => {
            notification.warning({
                message: '紧急事件',
                description: <>今日紧急待处理事务有 {handleNumber(data)} 条，请前往查看</>,
                placement: 'bottomRight'
            })
        }

        async function fetchData() {
            const res = await getHomeInformation(token)
            if (res) {
                setTimeLimit(res.timeLimit)
                setRiskLevels(res.risk)
                setCache('emergent', res.emergent)
                renderCategory(_.groupBy(res.categories, item => item.title))
                handleEmergent(res.emergent)
            }
        }
        fetchData()
    }, [token])

    const handleNumber = (data) => {
        const size = data.length
        return <span style={{ color: size === 0 ? "blue" : "red" }}>{size}</span>
    }

    const renderCategory = (categoryObj) => {
        const myChart = echarts.init(categoryRef.current)
        // 指定图表的配置项和数据
        const option = {
            title: {
                text: '业务分类图示'
            },
            tooltip: {},
            legend: {
                data: ['数量']
            },
            xAxis: {
                data: Object.keys(categoryObj),
                axisLabel: {
                    interval: 0,
                    rotate: 45
                }
            },
            yAxis: {
                minInterval: 1
            },
            series: [
                {
                    name: '数量',
                    type: 'bar',
                    colorBy: 'data',
                    data: Object.values(categoryObj).map(item => item[0]?.num)
                }
            ]
        };

        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option)
        window.onresize = () => {
            myChart.resize()
        }
    }

    const renderHeader = (name, title) => {
        return (
            <div className='home-list'>
                <div>{name}</div>
                <div>{title}</div>
            </div>
        )
    }

    const renderContent = (item) => {
        return (
            <>
                <div>{formatTimeLimit(item.title)}</div>
                <div>{item.num}</div>
            </>
        )
    }

    const onSelect = (value) => {
        const day = value.day()
        const weekday = ['天', '一', '二', '三', '四', '五', '六']
        message.info('当前选择日期：' + value.format('YYYY-MM-DD') + " 星期" + weekday[day])
    };

    return (
        <>
            <div className="site-card-wrapper home-container">
                <Row gutter={16}>
                    <Col span={8}>
                        <Card title="办理时限" bordered={border}>
                            <List
                                className='home-list-container home-scroll'
                                header={renderHeader("时限", "记录数量")}
                                dataSource={timeLimit}
                                renderItem={(item) => (
                                    <List.Item>
                                        {renderContent(item)}
                                    </List.Item>)
                                }
                            />
                        </Card>
                    </Col>
                    <Col span={8}>
                        <Card title="风险等级" bordered={border}>
                            <List
                                className='home-list-container'
                                header={renderHeader("等级", "记录数量")}
                                dataSource={riskLevels}
                                renderItem={(item) => (
                                    <List.Item>
                                        {renderContent(item)}
                                    </List.Item>)
                                }
                            />
                        </Card>
                    </Col>
                    <Col span={8}>
                        <Card
                            className='home-list-container'
                            cover={
                                <Calendar
                                    className='home-calendar'
                                    fullscreen={false}
                                    locale={configLocale}
                                    onSelect={onSelect}
                                />
                            }
                        >
                        </Card>
                    </Col>
                </Row>
            </div>
            <div ref={categoryRef} style={{ width: "100%", height: "300px", marginTop: '15px' }}></div>
        </>
    )
}